const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const { ProvidePlugin } = require("webpack");
const { PurgeCSSPlugin } = require("purgecss-webpack-plugin");
const glob = require("glob");
const path = require("path");

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

module.exports = {
  mode: "production",
  plugins: [
    new ProvidePlugin({
      axios: ["axios", "default"],
      dayjs: "dayjs",
    }), //shimming

    //对css进行TreeShaking
    new PurgeCSSPlugin({
      paths: glob.sync(`${path.resolve(__dirname, "../src")}/**/*`, { nodir: true }),
      safelist: function () {
        return {
          standard: ["body"],
        };
      },
    }),

    new MiniCssExtractPlugin(), //提取css
    //分析打包的插件
    new BundleAnalyzerPlugin(),
  ],

  //优化配置
  optimization: {
    //导入模块时，分析模块中的有哪些函数有被使用，哪些函数没有被使用，treeShake，一般还要配合terser插件使用
    usedExports: true,
    // chunkIds: "deterministic", //"natural" "named" "deterministic"
    splitChunks: {
      // chunks: "async",//默认值，对异步加载的模块进行分包
      chunks: "all", //第三方库全部分到一个包
      // maxSize: 20000, //当一个包大于指定的大小时候，继续进行拆包
      // minSize: 100, //将包拆分不小miniSize的包
      //notice:分出来的包未必会满足上面这个区域，
      //自己对需要进行分包的内容进行分包
      cacheGroups: {
        vendors: {
          test: /[\\/]node_module[\\/]/,
          // filename: "[name]_vendors.js",
          filename: "[name]_vendors.js",
          //  filename: "[id]_vendors.js",
        },
        utils: {
          test: /utils/,
          // filename: "[name]_utils.js",
          filename: "[id]_utils.js",
        },
      },
    },
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin(), //css代码简化
      new TerserPlugin({
        extractComments: false,
        terserOptions: {
          compress: {
            arguments: true,
            unused: true,
          },
          mangle: true,
          keep_fnames: true,
        },
      }), //js压缩插件 terserPlugin
    ],
  },
  //cdn打包
  externals: {
    //key:属性名 需要排除的框架名称
    //value:cdn提供的第三方包全局变量名称
    react: "React",
    axios: "axios",
    dayjs: "dayjs",
  },
};
